<template>
    <view class="makestory">
        <view class="makestory-top">
            <view class="makestory-left">
                <view class="makestory-left-title">开始减肥</view>
                <view class="makestory-left-selent">
                    <picker
                        :end="afterDateMax"
                        :start="request.formatDate('y/m/d', userInfo.createTime)"
                        mode="date"
                        @change="bindStartChange"
                    >
                        <view style="display: flex; flex-direction: row; align-items: center">
                            <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/icon3.png" mode=""></image>
                            <view>
                                <text v-if="form.startTime == ''" style="color: #cccccc">选择日期</text>
                                <text v-else style="color: #333333">{{ form.startTime }}</text>
                            </view>
                        </view>
                    </picker>
                </view>
                <view class="makestory-left-selent">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/icon4.png" mode=""></image>
                    <input
                        @input="beforeWeightChange"
                        @blur="blurBeforeWeightChange"
                        style="font-size: 24rpx; width: calc(100% - 80rpx); color: #333"
                        type="digit"
                        v-model="form.beforeWeight"
                        placeholder="体重"
                        border="none"
                        placeholder-style="color:#ccc"
                        maxlength="5"
                    />kg
                </view>
            </view>

            <view class="makestory-left">
                <view class="makestory-left-title">现在</view>
                <view class="makestory-left-selent">
                    <picker :start="afterDateMin" :end="afterDateMax" mode="date" @change="bindEndChange">
                        <view style="display: flex; flex-direction: row; align-items: center">
                            <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/icon3.png" mode=""></image>
                            <view>
                                <text v-if="form.endTime == ''" style="color: #cccccc">选择日期</text>
                                <text v-else style="color: #333333">{{ form.endTime }}</text>
                            </view>
                        </view>
                    </picker>
                </view>
                <view class="makestory-left-selent">
                    <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/icon4.png" mode=""></image>
                    <input
                        @input="afterWeightChange"
                        @blur="blurAfterWeightChange"
                        style="font-size: 24rpx; width: calc(100% - 80rpx); color: #333"
                        type="digit"
                        v-model="form.afterWeight"
                        placeholder="体重"
                        border="none"
                        placeholder-style="color:#ccc"
                        maxlength="5"
                    />kg
                </view>
            </view>
        </view>
        <view class="makestory-upload">
            <view class="makestory-upload-title">上传照片</view>
            <view class="makestory-upload-main">
                <view class="makestory-upload-left">
                    <image
                        style="
                            z-index: 2;
                            position: absolute;
                            float: right;
                            right: 0;
                            top: 0;
                            width: 128rpx;
                            height: 48rpx;
                        "
                        src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/before_icon.png"
                        mode=""
                    ></image>
                    <image
                        style="
                            z-index: 1;
                            position: absolute;
                            left: 0;
                            top: 0;
                            width: 100%;
                            height: 100%;
                            border-radius: 16rpx;
                        "
                        :src="form.beforePicAbsolute"
                    ></image>
                    <view style="z-index: 5" @click="chooseImage(1)" class="makestory-upload-btn">{{
                        form.beforePicAbsolute ? '更改图片' : '上传图片'
                    }}</view>
                </view>
                <view class="makestory-upload-left">
                    <image
                        style="
                            z-index: 2;
                            position: absolute;
                            float: right;
                            right: 0;
                            top: 0;
                            width: 128rpx;
                            height: 48rpx;
                        "
                        src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/homemenu/after_icon.png"
                        mode=""
                    ></image>
                    <image
                        style="
                            z-index: 1;
                            position: absolute;
                            left: 0;
                            top: 0;
                            width: 100%;
                            height: 100%;
                            border-radius: 16rpx;
                        "
                        :src="form.afterPicAbsolute"
                    ></image>
                    <view style="z-index: 5" @click="chooseImage(2)" class="makestory-upload-btn">{{
                        form.afterPicAbsolute ? '更改图片' : '上传图片'
                    }}</view>
                </view>
            </view>
        </view>

        <view class="makestory-upload" style="margin: 20rpx auto">
            <view class="makestory-upload-title">减肥心得</view>
            <view style="border-radius: 16rpx; margin: 0 30rpx; padding-bottom: 30rpx; width: calc(100% - 60rpx)">
                <textarea
                    style="
                        width: 100%;
                        height: 400rpx;
                        background-color: #f6f6f6;
                        padding: 20rpx;
                        box-sizing: border-box;
                        border-radius: 16rpx;
                        color: #333;
                    "
                    placeholder-style="color:#CCCCCC"
                    v-model="form.weightExperience"
                    placeholder="输入减肥心得"
                    maxlength="300"
                ></textarea>
                <!-- <u--textarea height=200 border='none' v-model="form.weightExperience" placeholder="输入减肥心得" ></u--textarea> -->
            </view>
        </view>

        <view style="height: 200rpx"></view>
        <view
            @click="creatStory()"
            class="footer"
            style="background-color: #fff; width: 100%; padding: 16rpx 0 20rpx; z-index: 99999"
        >
            <view class="footer-item"> 确认 </view>
        </view>
        <u-calendar :show="show" @confirm="confirm" @close="show = false"></u-calendar>
        <u-calendar :show="show1" @confirm="confirm1" @close="show1 = false"></u-calendar>
        <dynamic_success_pop :show="isShowSuccess" @close="closeBack()" :integral="score"></dynamic_success_pop>
        <xunzhang-pop-view :show="isShowXunZhang" :list="medalList" @close="closeXunZhang()"></xunzhang-pop-view>
    </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
    data() {
        return {
            show: false,
            show1: false,
            form: {
                afterPic: '',
                afterPicAbsolute: '',
                afterWeight: '',
                beforePic: '',
                beforePicAbsolute: '',
                beforeWeight: '',
                startTime: '',
                endTime: '',
                weightExperience: '',
                templateId: 1, //1 和 2
            },
            isShowSuccess: false,
            score: 0,
            isShowXunZhang: false,
            medalList: [],
            afterDateMax: '',
            afterDateMin: '',
        };
    },
    computed: {
        ...mapState(['isLogin', 'userInfo']),
    },
    onLoad(options) {
        this.form.templateId = options.type;
        this.requestUser();
        this.afterDateMax = this.getDate();
    },
    methods: {
        closeXunZhang() {
            this.isShowXunZhang = false;
            uni.navigateBack();
        },
        closeBack() {
            this.backEvent();
        },
        Getweight(e) {
            this.form.weightExperience = e.detail.value;
        },
        beforeWeightChange(e) {
            let that = this;
            var weight = e.detail.value;
            weight = weight.replace(/[^\d.]/g, '');
            weight = weight.replace(/\.{2,}/g, '.');
            weight = weight.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            weight = weight.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            if (weight.indexOf('.') < 0 && weight != '') {
                weight = parseFloat(weight);
            }

            that.$nextTick(function () {
                that.form.beforeWeight = weight;
            });
        },
        blurBeforeWeightChange(e) {
            var weight = e.detail.value;
            if (weight < this.form.afterWeight && this.form.afterWeight > 0) {
                weight = this.form.afterWeight;
            }
            if (typeof weight == 'string' && weight.indexOf('.') >= 0) {
                weight = parseFloat(weight).toFixed(2);
            }
            this.$nextTick(() => {
                this.form.beforeWeight = weight;
            });
        },
        afterWeightChange(e) {
            let that = this;
            var weight = e.detail.value;
            weight = weight.replace(/[^\d.]/g, '');
            weight = weight.replace(/\.{2,}/g, '.');
            weight = weight.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            weight = weight.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            if (weight.indexOf('.') < 0 && weight != '') {
                weight = parseFloat(weight);
            }
            that.$nextTick(function () {
                that.form.afterWeight = weight;
            });
        },
        blurAfterWeightChange(e) {
            var weight = e.detail.value;
            if (weight > this.form.beforeWeight && this.form.beforeWeight > 0) {
                weight = this.form.beforeWeight;
            }
            if (typeof weight == 'string' && weight.indexOf('.') >= 0) {
                weight = parseFloat(weight).toFixed(2);
            }
            this.$nextTick(() => {
                this.form.afterWeight = weight;
            });
        },
        requestUser() {
            this.request
                .httpTokenRequest(`/mp-api/wx/user/detail/${this.userInfo.uid}`, null, 'POST', true)
                .then((res) => {
                    if (res.code == 0) {
                        this.form.startTime = this.request.formatDate('y-m-d', res.data.registerTime);
                        this.afterDateMin = this.request.formatDate('y-m-d', res.data.registerTime);
                        if (res.data.weight > 0) {
                            this.form.beforeWeight = res.data.weight;
                        }
                    }
                });
        },
        bindEndChange(e) {
            var endDate = e.detail.value;
            this.form.endTime = endDate;
        },
        bindStartChange(e) {
            const startDate = e.detail.value;
            const startTmp = new Date(startDate).getTime();
            const endTmp = new Date(this.form.endTime).getTime();
            if (startTmp > endTmp) {
                this.form.endTime = '';
            }
            this.form.startTime = startDate;
            this.afterDateMin = startDate;
        },
        getDate() {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        creatStory() {
            if (
                this.form.afterPic == '' ||
                this.form.afterPicAbsolute == '' ||
                this.form.afterWeight == '' ||
                this.form.beforePic == '' ||
                this.form.beforePicAbsolute == '' ||
                this.form.beforeWeight == '' ||
                this.form.startTime == '' ||
                this.form.endTime == '' ||
                this.form.weightExperience == ''
            ) {
                uni.showToast({
                    title: '请完善信息!',
                    icon: 'error',
                });
                return;
            }
            if (this.form.afterWeight >= 1000 || this.form.beforeWeight >= 1000) {
                uni.showToast({
                    title: '请输入正确的体重',
                    icon: 'none',
                });
                return;
            }
            this.request.httpTokenJsonRequest('/mp-api/wx/story/publish', this.form, 'POST', false).then((res) => {
                if (res.code == 0) {
                    if (res.data.score.score > 0) {
                        this.isShowSuccess = true;
                        this.score = res.data.score.score;
                    } else {
                        if (res.data.score.score == 0) {
                            if (res.data.medal) {
                                if (
                                    res.data.medal.name != '' &&
                                    res.data.medal.name != undefined &&
                                    res.data.medal.name != null
                                ) {
                                    this.medalList.length = 0;
                                    this.medalList.push(res.data.medal);
                                    this.isShowXunZhang = true;
                                } else {
                                    uni.showModal({
                                        showCancel: false,
                                        confirmText: '确定',
                                        title: '发布成功',
                                        content: res.data.score.message,
                                        success: (res) => {
                                            if (res.confirm) {
                                                uni.navigateBack();
                                            }
                                        },
                                    });
                                }
                            } else {
                                uni.showModal({
                                    showCancel: false,
                                    confirmText: '确定',
                                    title: '发布成功',
                                    content: res.data.score.message,
                                    success: (res) => {
                                        if (res.confirm) {
                                            uni.navigateBack();
                                        }
                                    },
                                });
                            }
                        } else {
                            uni.showToast({
                                icon: 'success',
                                title: '发布成功',
                            });
                            setTimeout(() => {
                                uni.navigateBack();
                            }, 500);
                        }
                    }
                    if (res.data.medal) {
                        if (
                            res.data.medal.name != '' &&
                            res.data.medal.name != undefined &&
                            res.data.medal.name != null
                        ) {
                            this.medalList.length = 0;
                            this.medalList.push(res.data.medal);
                        }
                    }
                }
            });
        },
        backEvent() {
            if (this.medalList.length > 0) {
                this.isShowXunZhang = true;
                this.isShowSuccess = false;
            } else {
                uni.navigateBack();
            }
        },
        confirm(e) {
            e[0] = e[0].replace(/\-/g, '-');
            this.form.startTime = e[0];
            this.show = false;
        },
        confirm1(e) {
            e[0] = e[0].replace(/\-/g, '-');
            this.form.endTime = e[0];
            this.show1 = false;
        },
        chooseImage(type) {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                success: (res) => {
                    var filePath = res.tempFilePaths[0];
                    this.changeAvatar(filePath, type);
                },
            });
        },
        changeAvatar(fileUrl, type) {
            uni.showLoading({
                title: '图片上传中',
            });
            uni.uploadFile({
                url: this.request.baseUrl + '/mp-api/wx/common/upload',
                method: 'POST',
                header: {
                    'x-accesstoken': this.request.getToken(),
                },
                filePath: fileUrl,
                name: 'file',
                success: (res) => {
                    uni.hideLoading();
                    if (res.statusCode === 200) {
                        var dataBack = JSON.parse(res.data);
                        if (dataBack.code == 0) {
                            if (type == 1) {
                                this.form.beforePicAbsolute = dataBack.data.absolutePath;
                                this.form.beforePic = dataBack.data.path;
                            } else if (type == 2) {
                                this.form.afterPicAbsolute = dataBack.data.absolutePath;
                                this.form.afterPic = dataBack.data.path;
                            }
                        }
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                },
            });
        },
    },
};
</script>

<style scoped></style>
